package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.*;
import com.tanhua.common.pojo.tanhua.BlackList;
import com.tanhua.common.pojo.tanhua.Question;
import com.tanhua.common.pojo.tanhua.Settings;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.dubbo.pojo.UserLike;
import com.tanhua.dubbo.pojo.Visitors;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UsersService {

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private BlackListService blackListService;

    @Autowired
    private SettingsService settingsService;

    /**
     * 读取用户资料
     *
     * @param userId
     * @param huanxinID
     * @return
     */
    public UserInfoVo showUserInfo(Long userId, Long huanxinID) {
        User user = UserThreadLocal.get();
        Long id = user.getId();
        if (userId != null) {
            id = userId;
        } else if (huanxinID != null) {
            id = huanxinID;
        }

        UserInfo userInfo = userInfoService.findById(id);

        if (null == userInfo) {
            return null;
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setAge(userInfo.getAge() != null ? userInfo.getAge().toString() : null);
        userInfoVo.setAvatar(userInfo.getLogo());
        userInfoVo.setBirthday(userInfo.getBirthday());
        userInfoVo.setEducation(userInfo.getEdu());
        userInfoVo.setCity(userInfo.getCity());
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setId(userInfo.getUserId());
        userInfoVo.setIncome(userInfo.getIncome() + "K");
        userInfoVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
        userInfoVo.setNickname(userInfo.getNickName());
        userInfoVo.setProfession(userInfo.getIndustry());

        return userInfoVo;
    }

    /**
     * 保存用户信息
     *
     * @param userInfoVo
     * @return
     */
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setAge(Integer.valueOf(userInfoVo.getAge()));
        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(), "K", ""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");
        return this.userInfoService.updateUserInfoByUserId(userInfo);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return 统计数量的对象
     */
    public UserLikesCountVo queryUserLikesCount() {
        User user = UserThreadLocal.get();
        Long eachLikeCount = this.userLikeApi.eachLikeCount(user.getId());
        Long likeCount = this.userLikeApi.queryLikeCount(user.getId());
        Long fanCount = this.userLikeApi.queryFanCount(user.getId());
        UserLikesCountVo userLikesCountVo = new UserLikesCountVo();
        userLikesCountVo.setEachLoveCount(eachLikeCount);
        userLikesCountVo.setLoveCount(likeCount);
        userLikesCountVo.setFanCount(fanCount);
        return userLikesCountVo;
    }

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     *
     * @param type     1 互相关注 2 我关注 3 粉丝 4 谁看过我
     * @param page
     * @param pageSize
     * @param nickname
     * @return
     */
    public PageResult queryVisitors(Integer type, Integer page, Integer pageSize, String nickname) {
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        List<Long> userIds = new ArrayList<>();
        //1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch (type) {
            case 1: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryEachLikeList(user.getId(), page, pageSize);
                List<UserLike> records = pageInfo.getRecords();
                for (UserLike record : records) {
                    if (record.getUserId().longValue() != user.getId()) {
                        userIds.add(record.getUserId());
                    }
                }
                break;
            }
            case 2: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(user.getId(), page, pageSize);
                List<UserLike> records = pageInfo.getRecords();
                for (UserLike record : records) {
                    if (record.getLikeUserId().longValue() != user.getId()) {
                        userIds.add(record.getLikeUserId());
                    }
                }
                break;
            }
            case 3: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(user.getId(), page, pageSize);
                for (UserLike record : pageInfo.getRecords()) {
                    if (record.getUserId().longValue() != user.getId().longValue()) {
                        userIds.add(record.getUserId());
                    }
                }
                break;
            }
            case 4: {
                List<Visitors> visitorsList = this.visitorsApi.topVisitor(user.getId(), page, pageSize);
                for (Visitors visitors : visitorsList) {
                    if (visitors.getVisitorUserId().longValue() != user.getId()) {
                        userIds.add(visitors.getVisitorUserId());
                    }
                }
                break;
            }
            default:
                break;
        }

        if (CollectionUtils.isEmpty(userIds)){
            return pageResult;
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.isNotEmpty(nickname)) {
            queryWrapper.like("nick_name", nickname);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryList(queryWrapper);
        List<UserLikeListVo> userLikeListVoList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = new UserLikeListVo();
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setNickname(userInfo.getNickName());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            userLikeListVo.setEducation(userInfo.getEdu());
            // 判断是否喜欢ta
            String redisKey = "USER" + user.getId() + "LIKE" + userInfo.getUserId();
            userLikeListVo.setAlreadyLove(this.redisTemplate.hasKey(redisKey));

            Double score = this.recommendUserService.queryScore(user.getId(), userInfo.getUserId());
            userLikeListVo.setMatchRate(score.intValue());

            userLikeListVoList.add(userLikeListVo);
        }
        pageResult.setItems(userLikeListVoList);
        return pageResult;
    }

    /**
     * 粉丝 - 喜欢
     *
     * @param fansId
     * @return
     */
    public boolean likeFans(Long fansId) {
        User user = UserThreadLocal.get();
        String result = this.userLikeApi.saveUserLike(user.getId(), fansId);
        return StringUtils.isNotEmpty(result);
    }

    /**
     * 喜欢 - 取消
     *
     * @param likeId
     * @return
     */
    public boolean deleteLike(Long likeId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(), likeId);
    }

    /**
     * 设置陌生人问题 - 保存
     *
     * @param content
     * @return
     */
    public void saveQuestion(String content) {
        User user = UserThreadLocal.get();
        this.questionService.saveQuestion(user.getId(), content);
    }

    /**
     * 查询黑名单列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryBlackList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();

        // 获取分页对象
        IPage<BlackList> blackListIPage = this.blackListService.queryBlackList(user.getId(), page, pageSize);

        // 填充PageResult
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(new Long(blackListIPage.getTotal()).intValue());
        pageResult.setPages(new Long(blackListIPage.getPages()).intValue());

        // 如果黑名单列表为空，则直接返回pageResult
        List<BlackList> records = blackListIPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }

        List<Long> blackUserIds = new ArrayList<>();
        for (BlackList record : records) {
            blackUserIds.add(record.getBlackUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", blackUserIds);
        List<UserInfo> userInfoList = this.userInfoService.queryList(queryWrapper);

        List<BlackListVo> blackListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            BlackListVo blackListVo = new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setNickname(userInfo.getNickName());

            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    /**
     * 移除黑名单
     *
     * @param blackUserId
     * @return
     */
    public boolean deleteBlackList(Long blackUserId) {
        User user = UserThreadLocal.get();

        return this.blackListService.deleteByUserId(user.getId(), blackUserId);
    }

    /**
     * 用户通用设置 - 读取
     *
     * @return
     */
    public SettingsVo querySettings() {
        User user = UserThreadLocal.get();
        SettingsVo settingsVo = new SettingsVo();
        settingsVo.setId(user.getId());
        settingsVo.setPhone(user.getMobile());
        Settings settings = this.settingsService.querySettings(user.getId());
        if (settings != null){
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }
        // 查询设置的问题
        Question question = this.questionService.queryQuestion(user.getId());
        if (null != question) {
            settingsVo.setStrangerQuestion(question.getTxt());
        }

        return settingsVo;
    }

    /**
     * 更新通知设置
     *
     * @param likeNotification
     * @param pinglunNotification
     * @param gonggaoNotification
     */
    public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        User user = UserThreadLocal.get();
        this.settingsService.updateNotification(user.getId(), likeNotification, pinglunNotification, gonggaoNotification);
    }
}
